package com.example.appointment.repository;

import com.example.appointment.entity.HealthCheck;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface HealthCheckRepository extends JpaRepository<HealthCheck, Long> {
    Page<HealthCheck> findByUserId(Long userId, Pageable pageable);
    
    Page<HealthCheck> findByUserIdAndType(Long userId, String type, Pageable pageable);
    
    Page<HealthCheck> findByUserIdAndCreateTimeBetween(
            Long userId, 
            LocalDateTime startDate, 
            LocalDateTime endDate, 
            Pageable pageable
    );
    
    Page<HealthCheck> findByUserIdAndTypeAndCreateTimeBetween(
            Long userId, 
            String type, 
            LocalDateTime startDate, 
            LocalDateTime endDate, 
            Pageable pageable
    );
    
    @Query("SELECT COUNT(h) FROM HealthCheck h WHERE h.user.id = :userId")
    long countByUserId(@Param("userId") Long userId);
    
    @Query("SELECT COUNT(h) FROM HealthCheck h WHERE h.user.id = :userId AND h.createTime >= :startDate")
    long countByUserIdAndCreateTimeAfter(
            @Param("userId") Long userId,
            @Param("startDate") LocalDateTime startDate
    );
    
    @Query("SELECT COUNT(h) FROM HealthCheck h WHERE h.user.id = :userId AND h.createTime BETWEEN :startDate AND :endDate")
    long countByUserIdAndCreateTimeBetween(
            @Param("userId") Long userId,
            @Param("startDate") LocalDateTime startDate,
            @Param("endDate") LocalDateTime endDate
    );
    
    @Query("SELECT h FROM HealthCheck h WHERE h.user.id = :userId AND h.createTime >= :startDate")
    List<HealthCheck> findByUserIdAndCreateTimeAfter(
            @Param("userId") Long userId,
            @Param("startDate") LocalDateTime startDate
    );
    
    @Query("SELECT h FROM HealthCheck h WHERE h.user.id = :userId AND h.createTime BETWEEN :startDate AND :endDate")
    List<HealthCheck> findByUserIdAndCreateTimeBetween(
            @Param("userId") Long userId,
            @Param("startDate") LocalDateTime startDate,
            @Param("endDate") LocalDateTime endDate
    );
    
    @Query(value = "SELECT DATEDIFF(MAX(created_at), MIN(created_at)) + 1 FROM health_checks " +
            "WHERE user_id = :userId " +
            "AND created_at >= :startDate " +
            "GROUP BY DATE(created_at) " +
            "HAVING COUNT(*) > 0 " +
            "ORDER BY DATE(created_at)", nativeQuery = true)
    Integer getContinuousDays(
            @Param("userId") Long userId,
            @Param("startDate") LocalDateTime startDate
    );
} 